<?php

namespace App\Models;

use Dcat\Admin\Traits\HasDateTimeFormatter;

use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Storage;
use Laravel\Sanctum\HasApiTokens;


class User extends Model
{
    use HasDateTimeFormatter, HasApiTokens, Notifiable;

    protected $fillable = ['username', 'avatar', 'mobile', 'wx_open_id', 'balance'];
    protected $appends = ['avatar_url'];

    public function runErrand()
    {
        return $this->hasOne(RunErrand::class);
    }

    public function avatarUrl(): Attribute
    {
        if ($this->avatar) {
            $avatar = (str_starts_with($this->avatar, 'http://') || str_starts_with($this->avatar, 'https://')) ? $this->avatar : Storage::disk('oss')->url($this->avatar);
        } else {
            $avatar = null;
        }
        return Attribute::make(get: fn() => $avatar);
    }
}
